import { promises as fs } from 'fs';
import { join } from 'path';

interface SearchRequest {
  query: string;
  caseSensitive?: boolean;
  useRegex?: boolean;
}

interface SearchResult {
  filename: string;
  lineNumber: number;
  line: string;
}

export default defineEventHandler(async (event) => {
  if (getMethod(event) !== 'POST') {
    throw createError({
      statusCode: 405,
      statusMessage: 'Method Not Allowed'
    });
  }

  try {
    const body = await readBody<SearchRequest>(event);
    
    if (!body.query || body.query.trim() === '') {
      throw createError({
        statusCode: 400,
        statusMessage: '搜索关键词不能为空'
      });
    }

    const results = await searchInLogFiles(body);

    return {
      results,
      query: body.query,
      totalMatches: results.length
    };

  } catch (error: any) {
    console.error('Search error:', error);
    throw createError({
      statusCode: 500,
      statusMessage: error.message || '搜索失败'
    });
  }
});

async function searchInLogFiles(searchRequest: SearchRequest): Promise<SearchResult[]> {
  const { query, caseSensitive = false, useRegex = false } = searchRequest;
  const results: SearchResult[] = [];
  const logsDir = './logs';

  try {
    // 检查日志目录是否存在
    await fs.access(logsDir);
    const files = await fs.readdir(logsDir);

    if (files.length === 0) {
      throw new Error('没有找到日志文件，请先上传压缩包');
    }

    // 创建搜索正则表达式
    let searchRegex: RegExp;
    try {
      if (useRegex) {
        searchRegex = new RegExp(query, caseSensitive ? 'g' : 'gi');
      } else {
        const escapedQuery = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
        searchRegex = new RegExp(escapedQuery, caseSensitive ? 'g' : 'gi');
      }
    } catch (error) {
      throw new Error('正则表达式格式错误');
    }

    // 搜索每个文件
    for (const filename of files) {
      const filePath = join(logsDir, filename);
      
      try {
        const content = await fs.readFile(filePath, 'utf8');
        const lines = content.split('\n');

        lines.forEach((line, index) => {
          if (searchRegex.test(line)) {
            results.push({
              filename,
              lineNumber: index + 1,
              line: line.trim()
            });
          }
          // 重置正则表达式状态
          searchRegex.lastIndex = 0;
        });
      } catch (error) {
        console.warn(`跳过文件 ${filename}:`, error);
      }
    }

    // 按文件名和行号排序
    results.sort((a, b) => {
      if (a.filename !== b.filename) {
        return a.filename.localeCompare(b.filename);
      }
      return a.lineNumber - b.lineNumber;
    });

    // 限制结果数量以避免性能问题
    return results.slice(0, 1000);

  } catch (error: any) {
    if (error.code === 'ENOENT') {
      throw new Error('日志目录不存在，请先上传压缩包');
    }
    throw error;
  }
} 